package com.netkiller.mailmonitor.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.authn.oauth.GoogleOAuthHelper;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.netkiller.mailmonitor.core.APP_CONSTANTS;
import com.netkiller.mailmonitor.entity.AppUser;
import com.netkiller.mailmonitor.entity.OAuthEntity;
import com.netkiller.mailmonitor.service.AppUserService;
import com.netkiller.mailmonitor.service.ContextIOService;
import com.netkiller.mailmonitor.service.OauthService;
import com.netkiller.mailmonitor.vo.AppProperties;

/**
 * Controller  for oauth
 * @author JKB
 *
 */
@Controller
public class OauthController {

	@Autowired
	private AppProperties appProperties;

	@Autowired
	private AppUserService appUserService;

	@Autowired
	private ContextIOService contextIOService;

	@Autowired
	private OauthService oauthService;


	/**
	 * saves the user authorization token to database
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(APP_CONSTANTS.CALLBACK_PATH)
	public void acceptAccessToken(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		if (user == null) {
			response.sendRedirect(userService.createLoginURL(request
					.getRequestURI() + "?" + request.getQueryString()));

		} else {
			AppUser appUser = appUserService.getUser(user.getEmail());
			if (appUser != null) {

				String verifier = request.getParameter("oauth_verifier");
				String oauthToken = request.getParameter("oauth_token");
				/*System.out.println(appUser + "\n verifier : " + verifier
						+ "\n oauthToken: " + oauthToken);*/
				if (!StringUtils.isBlank(oauthToken)
						&& appUser.getOauthtoken().equals(oauthToken)) {
					OAuthEntity accessToken = oauthService.getAccessToken(
							verifier, appUser);
					appUser.setAccessTokenKey(accessToken.getKey());
					appUser.setAccessTokenSecret(accessToken.getSecret());
					/*String returnStr = contextIOService.addAccount(
							user.getEmail(), accessToken.getKey(),
							accessToken.getSecret());*/
					 contextIOService.addSource(appUser);
					//updateContextIOId(appUser, returnStr);
					//appUser.setContextioId(returnStr);
					appUserService.save(appUser);
					response.getWriter().println(
							"Successfully Authenticated to Email Statistics.");
				} else {
					response.getWriter()
							.println(
									"Invalid Credentials<br>Please ask your admin to resend authorization URL");
				}

			} else {
				response.getWriter()
						.println(
								"Logged In with wrong account. Please log out of all accounts and then retry.");
			}
		}
	}


}
